/*
 * @lc app=leetcode.cn id=106 lang=cpp
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    TreeNode* digui(vector<int>& inorder, vector<int>& postorder, int lin, int rin, int lpost, int rpost)
    {
        if(lin > rin || lpost > rpost) return nullptr;
        TreeNode* root = new TreeNode(postorder[rpost]);
        for(int i = lin; i <= rin; i++)
        {
            if(inorder[i] == postorder[rpost])
            {
                root->left = digui(inorder, postorder, lin, i - 1, lpost, lpost + i - lin - 1);
                root->right = digui(inorder, postorder, i + 1, rin, lpost + i - lin, rpost - 1);
                return root;
            }
        }
        return nullptr;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return digui(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
    }
};
// @lc code=end

